//
//  RHLocalEnergyFullVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2024/4/8.
//

#import "RHLocalEnergyFullVC.h"
#import "RHLocalEnergyChartView.h"
#import "DevChartModel.h"
#import "DevChartParamsModel.h"
#import "RHLocalSettingModel.h"
#import "RHBleCmdData.h"
#import "RHLocalEnergyFullVC.h"
#import "CBLEDataParse.h"
#import "RHBleCmdManager.h"
#import "SYChartTool.h"

@interface RHLocalEnergyFullVC ()
@property (nonatomic ,strong) RHLocalEnergyChartView *chartView;

@property (nonatomic ,strong) DevChartModel *chartModel;

@property (nonatomic ,strong) NSArray *cmdArray;

@property (nonatomic ,strong) NSTimer *timer;

@property (nonatomic ,strong) NSMutableDictionary *dataDic;

@property (nonatomic ,strong) NSMutableArray *chartDataArr;
@end

@implementation RHLocalEnergyFullVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [ProgressHUDManage shareObject].showLoadingTips = NO;
    [self setupUI];
    [self createCmd];
    [self getChartData];
    [self startReadDeviceInfo];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [ProgressHUDManage shareObject].showLoadingTips = YES;
}

-(void)createCmd
{
    NSArray *cmdArr = @[@{
        @"field":@"Ems_PPG_Day",
        @"regAddr":@(270),
        @"bitWidth":@(32),
        @"ratio":@"0.1",
        @"cmdType":@(LocalSettingType_EMS)
    },@{
        @"field":@"Ems_GGE_Day",
        @"regAddr":@(276),
        @"bitWidth":@(32),
        @"ratio":@"0.1",
        @"cmdType":@(LocalSettingType_EMS)
    },@{
        @"field":@"Ems_LE_Day",
        @"regAddr":@(280),
        @"bitWidth":@(32),
        @"ratio":@"0.1",
        @"cmdType":@(LocalSettingType_EMS)
    },@{
        @"field":@"Ems_GPE_Day",
        @"regAddr":@(278),
        @"bitWidth":@(32),
        @"ratio":@"0.1",
        @"cmdType":@(LocalSettingType_EMS)
    }];
    NSMutableArray *mtbArr = [NSMutableArray array];
    [cmdArr enumerateObjectsUsingBlock:^(NSDictionary  *_Nonnull dic, NSUInteger idx, BOOL * _Nonnull stop) {
        RHLocalSettingModel *settingModel = [RHLocalSettingModel yy_modelWithJSON:dic];
        [mtbArr addObject:settingModel];
    }];
    self.cmdArray = mtbArr.copy;
}

-(void)getChartData
{
    [[RHBleCmdManager shareMnger] readDeviceInfoFromBle:self.cmdArray];
}


-(void)startReadDeviceInfo
{
    [self.timer invalidate];
    self.timer = nil;
    self.timer = [RHCustomTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(getChartData) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop]addTimer:self.timer forMode:NSRunLoopCommonModes];
}
-(void)stopReadDeviceInfo{
    [self.timer invalidate];
    self.timer = nil;
}

-(void)receiveDeviceMsg:(NSNotification*)no
{
    NSDictionary *dic = [no object];
    if(dic.allKeys.count==0)return;

    NSLog(@"------>收到设备信息:%@",dic);
  
            
   
    [self.cmdArray enumerateObjectsUsingBlock:^(RHLocalSettingModel * _Nonnull obj, NSUInteger index, BOOL * _Nonnull stop) {
        if(obj.regAddr == [dic[CMD_ADDRESS] integerValue]){
            
            NSData *data = dic[CMD_ADDRESS_VALUE];
            NSString *parse_content = [CBLEDataParse parseData:data settingModel:obj];
            NSLog(@"---->%@ = %@",obj.field,parse_content);

            [self.dataDic setObject:parse_content forKey:obj.field];
          
            
            NSLog(@"---->曲线数据:%@",self.dataDic);
        }
           
    }];
    

}

//数据左移
-(void)shiftChartData:(NSDictionary *)dic
{
    if(self.chartDataArr.count>=10){
        [self.chartDataArr removeObjectAtIndex:0];
        [self.chartDataArr addObject:dic];
    }else{
        for (int i = 0; i < 10; i ++) {
            NSMutableDictionary *mtbDic = [NSMutableDictionary dictionary];
            for (NSString *key in dic.allKeys) {
                [mtbDic setObject:dic[key] forKey:key];
            }
            [self.chartDataArr addObject:mtbDic.copy];
        }
    }
    self.chartModel.allDataArray = self.chartDataArr;
    [self.chartView setChartModel:self.chartModel];
}

-(void)sendCmdFinish
{
    NSInteger timeInterval = [[NSDate date]timeIntervalSince1970]*1000;
    NSString *timeStr = [NSString stringWithFormat:@"%ld",timeInterval];
    [self.dataDic setObject:timeStr forKey:@"time"];
    [self.dataDic setObject:@"HH:mm:ss" forKey:@"timeFormat"];//电芯电压X时间定制格式,展示秒数
    [self shiftChartData:self.dataDic.mutableCopy];
}


- (void)setupUI{
    
    ADD_MESSAGE(BLEMSG_PHERAL_SENDMSG_ACK,receiveDeviceMsg:);
    ADD_MESSAGE(BLEMSG_PHERAL_SENDMSG_FINISH,sendCmdFinish);
    NSDictionary *dict = [SYChartTool readLocalJsonFileWithName:@"Local_DeviceEnergy"];
    DevChartParamsModel *paramsModel = [DevChartParamsModel yy_modelWithDictionary:dict];
    self.chartModel = [paramsModel.chartList firstObject];
    NSInteger timeInterval = [[NSDate date]timeIntervalSince1970];
    self.chartModel.curTime = [NSString stringWithFormat:@"%ld",timeInterval];
    
    _chartView = [[RHLocalEnergyChartView alloc] initWithFrame:CGRectMake(kSafe_top, 0,kUI_WINDOW_H - kSafe_top,kUI_WINDOW_W - kSafe_bottom) type:1];
    [self.bgView addSubview:_chartView];
    
    kWeakSelf;
    
    QMUILabel *titleLab = [QMUILabel labelWithFont:kSYSTEMFONT(16) textColor:kRGB(63, 68, 67)];
    titleLab.text = @"能量实时曲线".rh_localized;
    [self.view addSubview:titleLab];
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(25);
        make.centerX.mas_offset(0);
    }];
    
    
    //全屏
    QMUIButton *backBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setImagePosition:QMUIButtonImagePositionRight];
    [backBtn setImage:[UIImage imageNamed:@"back_icon"] forState:UIControlStateNormal];
    [self.view addSubview:backBtn];
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.equalTo(@(CGSizeMake(40, 40)));
        make.left.mas_offset(20);
        make.centerY.equalTo(titleLab);
    }];
    [[backBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        AppDelegate * delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
           delegate.allowRotate = 0;
        
        [weakSelf.timer invalidate];
        weakSelf.timer = nil;
        
        if(@available(iOS 16.0, *)) {
            [weakSelf.navigationController setNeedsUpdateOfSupportedInterfaceOrientations];
            NSArray *array = [[[UIApplication sharedApplication] connectedScenes] allObjects];
            UIWindowScene *ws = (UIWindowScene *)array[0];
            UIWindowSceneGeometryPreferencesIOS *geometryPreferences = [[UIWindowSceneGeometryPreferencesIOS alloc] init];
            geometryPreferences.interfaceOrientations = UIInterfaceOrientationMaskPortrait;
            [ws requestGeometryUpdateWithPreferences:geometryPreferences errorHandler:^(NSError * _Nonnull error) {
                 //业务代码
            }];
        }else{
            NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
            [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
        }
        [weakSelf.navigationController popViewControllerAnimated:YES];
    }];
    
   
    
    
    
    [_chartView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.mas_offset(0);
        make.top.equalTo(titleLab.mas_bottom).offset(20);
        make.right.mas_offset(-15);
    }];

 
//    [self.chartView setChartModel:self.chartModel];
   
}


-(NSMutableDictionary *)dataDic
{
    if(!_dataDic){
        _dataDic = [NSMutableDictionary dictionary];
    }
    return  _dataDic;
}

-(NSMutableArray *)chartDataArr
{
    if(!_chartDataArr){
        _chartDataArr = [NSMutableArray array];
    }
    return  _chartDataArr;
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
@end
